import { JsonGroup, JsonPathGroup, JsonPathRuleGroup } from '../types';
import { uuid } from '../utils';

export function addPathFromJsonGroup(jsonGroup: JsonGroup) {
  let newState = jsonGroup;

  function _processNode(item: JsonPathGroup | JsonPathRuleGroup) {
    if (!item.path) {
      item.path = uuid();
    }
    const rules = item.rules;
    if (rules) {
      for (let id in rules) {
        _processNode(rules[id] as JsonPathRuleGroup)
      }
    }
  }

  _processNode(jsonGroup as JsonPathGroup);

  return {...newState};
}

export function getJsonGroup(state: JsonGroup) {
  let newState = state;

  function _processNode(item: JsonPathGroup | JsonPathRuleGroup) {
    if (item.path) {
      delete item.path;
    }
    const rules = item.rules;
    if (rules) {
      for (let id in rules) {
        _processNode(rules[id] as JsonPathRuleGroup)
      }
    }
  }

  _processNode(state as JsonPathGroup);

  return {...newState};
}
